/**
 * Copyright (c) 2014-2018, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。
 * <p>
 * 你可以假设每种输入只会对应一个答案。但是，你不能重复利用这个数组中同样的元素。
 * <p>
 * 示例:
 * <p>
 * 给定 nums = [2, 7, 11, 15], target = 9
 * <p>
 * 因为 nums[0] + nums[1] = 2 + 7 = 9
 * 所以返回 [0, 1]
 *
 * @author Xue Xue (xuexue1@huli.com)f
 * @version $Id$
 * @since 2019/3/6
 */
public class Q1 {

    //这个答案对[3,3],6会返回错误.
    public static int[] WrongTwoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i : map.keySet()) {
            if (map.containsKey(target - i)) {
                return new int[]{map.get(i), map.get(target - i)};
            }
        }
        return null;
    }

    public static int[] CorrectTwoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i]) && i != map.get(target - nums[i])) {
                return new int[]{i, map.get(target - nums[i])};
            }
        }
        return null;
    }

    public static int[] CorrectTwoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{i, map.get(target - nums[i])};
            }
            map.put(nums[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println("请输入数组长度：");
        Scanner scanner = new Scanner(System.in);
        int arrLen = scanner.nextInt();
        System.out.println("请输入数字序列，以空格区分");
        int nums[] = new int[arrLen];
        for (int i = 0; i < arrLen; i++) {
            nums[i] = scanner.nextInt();
        }
        System.out.println("请输入TargetNumber");
        int target = scanner.nextInt();
        scanner.close();
        System.out.println(JSON.toJSONString(CorrectTwoSum(nums, target)));
    }
}
